package com.baitiaojun.web.core.filter;

import com.baitiaojun.common.constants.Constants;
import com.baitiaojun.web.core.utils.WebUtils;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * 对HttpServletRequest进行增强, 可以重复获取json参数
 */
public class ServletRequestCacheWrapper extends HttpServletRequestWrapper {

    /**
     * json数据缓存
     */
    private final byte[] body;

    /**
     * 构建可重复获取json参数的请求对象
     * @param request
     * @param response
     */
    public ServletRequestCacheWrapper(HttpServletRequest request, HttpServletResponse response) throws IOException {
        super(request);
        String utf8 = Constants.UTF8;
        request.setCharacterEncoding(utf8);
        response.setCharacterEncoding(utf8);
        body = WebUtils.getJsonStr(request).getBytes(utf8);
    }

    /**
     * 可重复获取json请求参数
     * @return
     * @throws IOException
     */
    @Override
    public BufferedReader getReader() {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

    /**
     * 从缓存的请求体获取请求的json参数
     * @return
     */
    @Override
    public ServletInputStream getInputStream() {
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body);
        return new ServletInputStream() {
            @Override
            public int available() {
                return byteArrayInputStream.available();
            }

            @Override
            public int read() {
                return byteArrayInputStream.read();
            }

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }
        };
    }
}
